package rexsee.core.widget;

import rexsee.core.menu.PopMenuItem;
import rexsee.core.style.StyleSheet;
import android.content.Context;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;

public class Tab extends LabelDiv {

	public final StyleSheet styleNormal;
	public final StyleSheet stylePressed;
	public final StyleSheet styleSelected;

	public Runnable downRunnable;
	public Runnable upRunnable;

	public Runnable extraRunnable = null;

	public Tab(final Context context, final PopMenuItem item) {
		super(context);
		styleNormal = item.styleNormal.clone();
		stylePressed = item.stylePressed.clone();
		styleSelected = item.styleSelected.clone();
		try {
			downRunnable = item.downRunnable;
			upRunnable = item.upRunnable;
			this.setDivId(item.id);
			this.setClickable(true);
			this.setOnTouchListener(new View.OnTouchListener() {
				@Override
				public boolean onTouch(View v, MotionEvent event) {
					if (isSelected()) return false;
					if (downRunnable == null && upRunnable == null) return false;
					int action = event.getAction();
					if (action == MotionEvent.ACTION_DOWN) {
						styleSheet = stylePressed;
						setLabelStyle();
						if (downRunnable != null) downRunnable.run();
					} else if (action == MotionEvent.ACTION_UP) {
						if (styleSheet.equals(stylePressed)) {
							cancelPressed();
							if (extraRunnable != null) extraRunnable.run();
							if (upRunnable != null) upRunnable.run();
						}
					} else if (action == MotionEvent.ACTION_CANCEL) {
						cancelPressed();
					} else if (action == MotionEvent.ACTION_MOVE) {
						float x = event.getX();
						float y = event.getY();
						if (x < 0 || x > v.getWidth() || y < 0 || y > v.getHeight()) cancelPressed();
					}
					return false;
				}
				private void cancelPressed() {
					styleSheet = styleNormal;
					setLabelStyle();
				}
			});
			setSelected(false);
		} catch (Exception e) {
			Toast.makeText(context, "TabBar:" + e.getLocalizedMessage(), Toast.LENGTH_LONG).show();
		}
	}

	@Override
	public void setStyle(String style) {
		styleSheet.parseStyle(style);
		setLabelStyle();
		styleNormal.parseStyle(style);
		stylePressed.parseStyle(style);
		styleSelected.parseStyle(style);
	}
	public void setStyle(String normalStyle, String pressedStyle, String selectedStyle) {
		styleSheet.parseStyle((isSelected()) ? selectedStyle : normalStyle);
		setLabelStyle();
		styleNormal.parseStyle(normalStyle);
		stylePressed.parseStyle(normalStyle).parseStyle(pressedStyle);
		styleSelected.parseStyle(normalStyle).parseStyle(selectedStyle);
	}
	@Override
	public void setSelected(boolean selected) {
		styleSheet = (selected) ? styleSelected : styleNormal;
		setLabelStyle();
	}
	@Override
	public boolean isSelected() {
		return (styleSheet.equals(styleSelected)) ? true : false;
	}

	public void destroy() {
		styleNormal.destroy();
		stylePressed.destroy();
		styleSelected.destroy();
	}

}
